import {
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Pagination,
  Popconfirm,
  Row,
  Table,
  Upload,
} from "antd";
import { useEffect, useState } from "react";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { useSelector, useDispatch } from "react-redux";
import {
  asyncGetPageList,
  asyncAddTradeMark,
  asyncUpdateTrade,
  asyncRemove,
} from "@/app/trademarkSlice";
import type { TradeMarkData } from "@/api/trademark";
import { store, storeData } from "@/app/store";
import { RcFile, UploadProps} from "antd/lib/upload";
// import UploadFile from "antd/lib/upload"
// "import UploadFile from "antd/lib/upload"
import type { UploadChangeParam } from "antd/es/upload";
import { UploadFile } from "antd/lib/upload/interface";

export default function TradeMark() {
  const dispatch = useDispatch();
  // const [loading, setLoading] = useState(false);
  // 回显数据的imgurl
  const [imageUrl, setImageUrl] = useState<string>();
  // logoUrl数据
  // const [logoUrl,setLogoUrl]= useState

  // 定义页数的state数据
  let [total, setTotal] = useState(0);
  // 定义当前页的state数据
  let [current, setCurrent] = useState(1);
  // 定义每页数量变化的state数据
  let [pageSize, setPageSize] = useState(3);
  // 定义
  let [tradeList, setTradeList] = useState<TradeMarkData[]>([]);
  // 定义数据判断是添加还是修改的删除
  const [row, setRow] = useState<TradeMarkData>({
    id: 0,
    tmName: "",
    logoUrl: "",
  });
  // 获取响应式的tradeMark数据-定义state数据的类型
  // let data = useSelector(state => (state as storeData).tardemark);
  // // console.log(data,'84356847648965768709809')
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();

  // 点击添加显示对话框
  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
    setImageUrl("");
    setRow({
      id: 0,
      tmName: "",
      logoUrl: "",
    });
  };

  // 点击修改按钮显示对话框
  const showDetail = (row: TradeMarkData) => {
    // 如果使用v-model收集数据此处需要自己创建一个新的数据不能在原数据进行修改
    setIsModalOpen(true);
    form.setFieldsValue(row);
    setImageUrl(row.logoUrl);                              
    setRow(row);
  };

  // 表单校验成功
  const onFinish = async (values: any) => {
    //  console.log(values,'values')
    // 获取表单输入的值
    //  let values = form.getFieldsValue();
    // console.log(values, "48356783448546");
    let obj: TradeMarkData = {
      tmName: values.tmName,
      logoUrl: imageUrl as string,
    };

    // console.log(row)
    if (row.id) {
      obj.id = row.id;
      await dispatch<any>(asyncUpdateTrade(obj));
      message.success({
        content: "修改成功",
      });
      // 修改图片的数据
      setImageUrl(row.logoUrl);
      getPageList(current);
    } else {
      // console.log('tianja')
      await dispatch<any>(asyncAddTradeMark(obj));
      message.success({
        content: "添加成功",
      });
      //  计算总页数 总条数/每页数量存在18.3直接舍弃会出现问题+1向下取整
      // console.log(Math.ceil(total/pageSize))
      getPageList(Math.floor(total / pageSize + 1));
      //  console.log(pageSize)
    }
    // 设置对话框关闭
    setIsModalOpen(false);
  };

  //  点击遮罩层或右上角叉或取消按钮的回调
  const cancelButton = () => {
    //  将对话框关闭
    setIsModalOpen(false);
  };

  // 对话框取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 实现删除按钮的数据
  const [del,setDelete] = useState<number>(0)

  // 删除消息盒子确定按钮
  const confirm = async (row: TradeMarkData) => {
    await dispatch<any>(asyncRemove(row.id as number));
    message.success(`${row.tmName}`);
    // 获取redux当中的数据,判断数组的长度,如果是返回上一页
    // setTimeout(() => {
      let data = store.getState().tardemark || {};
      // 使用三元运算符进行判断
      data.records.length - 1 ? getPageList(current):getPageList(current - 1)
  };

  // 删除消息盒子取消按钮
  const cancel = (row: TradeMarkData) => {
    message.error(`${row.tmName}`);
  };

  //  获取trademark列表的函数
  const getPageList = async (page = 1) => {
    // 设置默认值为1
    // 上边括号不可直接书写异步
    await dispatch<any>(asyncGetPageList({ page: page, limit: pageSize }));
    //page的值为page传入的值,添加传递的值并不是curren写current会存在问题
    let data = store.getState();
    setTradeList(data.tardemark.records);
    setCurrent(data.tardemark.current);

    setTotal(data.tardemark.total);
  };

  //挂载完成的时候发送ajax请求
  useEffect(() => {
    getPageList(current);
  }, [current, pageSize]);
  // []写上数据会在当前数据变化的时候执行

  // 此处的数据是表格的数据
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      dataIndex: "id",
      align: "center",
      width: 70,
      render: (x: any, y: any, index: number) => {
        //  console.log(index)
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      // 列数据在数据项当中对应的路径
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      render: (data: string) => {
        // 当前属性对应的值
        // console.log(data, "454768679");
        return <img width="80" src={data} alt="" />;
      },
    },
    {
      title: "操作",
      render: (row: TradeMarkData) => {
        // 当前行的详细信息
        // console.log(row)
        return (
          <div>
            <Button
              icon={<EditOutlined />}
              type="primary"
              onClick={() => {
                showDetail(row);
              }}
            >
              修改
            </Button>
            <Popconfirm
              title={`你确定要删除${row.tmName}`}
              onConfirm={() => {
                confirm(row);
              }}
              onCancel={() => {
                cancel(row);
              }}
              okText="确定"
              cancelText="取消"
            >
              <Button
                className="ml"
                icon={<DeleteOutlined />}
                danger
                type="primary"
              >
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  //   上传文件之前的回调函数
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  // 数据变化的时候触发的回调函数
  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    // console.log(info.file)
    if (info.file.status === "uploading") {
      // setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setImageUrl(info.file.response.data);
      // console.log(info.file.response.data,'8954659458657658798')
    }
  };

  // 上传的时候
  const uploadButton = (
    <div>
      {/* <PlusOutlined> */}
      <div style={{ marginTop: -12, fontSize: 50 }}>+</div>
      {/* </PlusOutlined> */}
    </div>
  );

  // 解决upload放在组件当中的初始化报错的问题
  const normFile = (e: any) => {
    // console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  return (
    <div>
      <Card>
        <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
          添加
        </Button>
        <Modal
          onCancel={cancelButton}
          title={imageUrl ? "修改品牌" : "添加品牌"}
          visible={isModalOpen}
          footer={null}
        >
          <Form name="basic" form={form} autoComplete="off" onFinish={onFinish}>
            <Form.Item
              label="品牌名称"
              name="tmName"
              rules={[{ required: true, message: "请输入品牌名称!" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
               className="bl"
              label="品牌LOGO"
              name="logoUrl"
              // 处理upload放在Item当中的时候会报错用下边两个
              valuePropName="logoUrl"
              getValueFromEvent={normFile}
              rules={[{ required: true, message: "上传图片不能为空" }]}
            >
              <Upload
                listType="picture-card"
                showUploadList={false}
                action="/app-dev/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
                // className="bl"
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
            <Form.Item className="h-20 mr">
              <Button htmlType="button" type="primary" onClick={handleCancel}>
                取消
              </Button>
              {/* onClick={handleOk} */}
              <Button htmlType="submit" className="ml">
                确认
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
      <Card>
        {/* 表格部分 */}
        <Table
          rowKey={"id"}
          bordered
          dataSource={tradeList}
          columns={columns}
          pagination={false}
        />
        {/* 分页列表 */}
        <div className="h-20"></div>
        <Pagination
          showSizeChanger
          pageSize={pageSize}
          current={current}
          pageSizeOptions={[3, 5, 7, 9]}
          // 添加onChange事件
          onChange={(page: number, pageSize: number) => {
            // 设置当前页
            setCurrent(page);
            // 设置每页数量
            setPageSize(pageSize);
          }}
          total={total}
          showTotal={(total) => `总页数${total}`}
        />
        {/* onClick={showModal} */}
      </Card>
    </div>
  );
}
